<template>
    <LayoutRightContainer :breadcrumb="breadcrumb">
        <div :class="$style['main-container']">
            <UserGroupComponents ref="userGroupRef" @node-click="handleNodeClick" @delete="deleteUserGroup" />
            <div :class="$style['table-container']">
                <el-form :inline="true" :class="$style['form-wrapper']">
                    <el-form-item>
                        <el-input v-model="searchForm.user" placeholder="人员姓名" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="searchForm.mobile" placeholder="手机号码" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="searchForm.job_number" placeholder="工号" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="searchForm.type" placeholder="人员类型" clearable>
                            <el-option label="内部员工" :value="1" />
                            <el-option label="外部访客" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchForm.page = 1; initUserData()">查询</el-button>
                    </el-form-item>
                </el-form>
                <div :class="$style['tools-container']">
                    <el-link :underline="false" type="success" :icon="Plus" @click="openAddDrawer({})">
                        添加
                    </el-link>
                    <el-link :underline="false" type="danger" :icon="Delete" :disabled="ids.length === 0"
                        @click="remove(ids)">
                        删除
                    </el-link>
                    <el-link :underline="false" type="success" :icon="Switch" :disabled="ids.length === 0"
                        @click="openSwitchGroupDialog(ids)">
                        切换组织
                    </el-link>
                    <el-link :underline="false" type="primary" :icon="Download" :disabled="ids.length === 0"
                        @click="exportUser(ids)">
                        导出人员档案
                    </el-link>
                    <el-link :underline="false" type="primary" :icon="Download" :disabled="ids.length === 0"
                        @click="exportUserAvatar(ids)">
                        导出人员照片
                    </el-link>
                    <!-- <el-link :underline="false" type="primary" :icon="UploadFilled">
                        批量导入
                    </el-link> -->
                </div>
                <el-table :data="tableData" @selection-change="handleSelectionChange" :class="$style['table-wrapper']">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="人员姓名" prop="name" align="center" />
                    <el-table-column label="人员组织" prop="group_name" align="center" />
                    <el-table-column label="员工性别" align="center">
                        <template #default="{ row }">
                            <span>{{ row.gender == 1 ? '男' : '女' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="人员照片" align="center">
                        <template #default="{ row }">
                            <el-avatar shape="square" :size="50" :src="row.avatar" />
                        </template>
                    </el-table-column>
                    <el-table-column label="联系电话" prop="mobile" align="center" width="130" />
                    <el-table-column label="员工卡号" prop="job_number" align="center" />
                    <el-table-column label="证件类型" align="center">
                        <template #default="{ row }">
                            <span>{{ row.id_type == 1 ? '身份证' : '护照' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="证件号码" prop="id_number" align="center" width="175" />
                    <el-table-column label="人员类型" align="center">
                        <template #default="{ row }">
                            <span>{{ row.type == 1 ? '内部员工' : '外部访客' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="出生日期" prop="birthday" align="center" width="120" />
                    <el-table-column label="籍贯" prop="native" align="center" />
                    <el-table-column label="有效期" prop="valid_date" align="center" />
                    <el-table-column label="操作" align="center" width="140" fixed="right">
                        <template #default="{ row }">
                            <div :class="$style['tools-wrapper']">
                                <el-link :underline="false" type="primary" :icon="Edit" @click="openAddDrawer(row)">
                                    编辑
                                </el-link>
                                <el-link :underline="false" type="danger" :icon="Delete" @click="remove([row.id])">
                                    删除
                                </el-link>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div :class="$style['flex-end']">
                    <el-pagination small background layout="sizes,total,prev, pager, next" :total="searchForm.total"
                        :hide-on-single-page="false" v-model:current-page="searchForm.page"
                        v-model:page-size="searchForm.limit" :page-sizes="[20, 50, 100, 200]"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </LayoutRightContainer>
    <AddUserComponents ref="addUserComponentsRef" @success="initUserData" />
    <SwitchGroupComponents ref="switchGroupRef" @success="initUserData" />
</template>
<script setup>
import { ref } from 'vue'
import { Edit, Delete, Plus, Switch, Download, UploadFilled } from '@element-plus/icons-vue'
import LayoutRightContainer from '@/views/layout-right-container.vue'
import UserGroupComponents from './components/UserGroupComponents.vue'
import AddUserComponents from './components/AddUserComponents.vue'
import SwitchGroupComponents from './components/SwitchGroupComponents.vue'
import {
    fetchUserBasic, fetchUserRemove, fetchUserExport,
    fetchUserExportAvatar
} from '@/api/user.services'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
const switchGroupRef = ref(null)
const userGroupRef = ref(null)
const addUserComponentsRef = ref(null)
const breadcrumb = ref([
    { label: '系统管理' },
    { label: '用户管理' },
    { label: '人员管理' }
])
const searchForm = ref({
    page: 1,
    limit: 20,
    total: 0
})
const handleNodeClick = (data) => {
    searchForm.value.page = 1
    searchForm.value.group_id = data.id
    initUserData()
}
const tableData = ref([])
const ids = ref([])
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.id)
}
const initUserData = async () => {
    const result = await fetchUserBasic(searchForm.value)
    if (result.code == 1) {
        tableData.value = result.data.data
        searchForm.value.total = result.data.total
    }
}
initUserData()
const deleteUserGroup = () => {
    searchForm.value.page = 1
    searchForm.value.group_id = null
    initUserData()
}
const handleSizeChange = val => {
    searchForm.value.page = 1
    searchForm.value.limit = val
    initUserData()
}
const handleCurrentChange = val => {
    searchForm.value.page = val
    initUserData()
}
const remove = async (ids) => {
    try {
        await ElMessageBox.confirm('是否删除选择的人员', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        const result = await fetchUserRemove({ ids: ids })
        if (result.code == 1) {
            ElMessage.success('删除成功')
            initUserData()
        }
    } catch (error) {
        console.log(error)
    }
}
const openAddDrawer = (row) => {
    addUserComponentsRef.value.open(row)
}
const openSwitchGroupDialog = (ids) => {
    switchGroupRef.value?.open(ids)
}
/***
 * @description: 导出人员档案
 * @param {*} ids
 * @return {*}
 * */
const exportUser = async (ids) => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在导出...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
        // 向后端请求导出文件
        const response = await fetchUserExport({ ids: ids })
        // 隐藏“正在导出”提示框
        loading.close()
        // 创建下载链接并触发下载
        const blob = response
        const link = document.createElement('a')
        const fileName = '人员档案' + new Date().toLocaleString() + '.xlsx'  // 你可以动态设置文件名，或从后端获取
        link.href = URL.createObjectURL(blob)
        link.download = fileName  // 设置文件下载的名字
        link.click()  // 触发下载
    } catch (error) {
        // 处理错误
        loading.close()
        ElMessage.error('导出失败')
    }
}
/***
 * @description: 导出人员头像
 * @param {*} ids
 * @return {*}
 * */
const exportUserAvatar = async (ids) => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在导出...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
        // 向后端请求导出文件
        const response = await fetchUserExportAvatar({ ids: ids })
        // 隐藏“正在导出”提示框
        loading.close()
        // 创建下载链接并触发下载
        const blob = response
        const link = document.createElement('a')
        const fileName = '人员头像' + new Date().toLocaleString() + '.zip'  // 你可以动态设置文件名，或从后端获取
        link.href = URL.createObjectURL(blob)
        link.download = fileName  // 设置文件下载的名字
        link.click()  // 触发下载
    } catch (error) {
        // 处理错误
        loading.close()
        ElMessage.error('导出失败')
    }
}
</script>
<style lang="scss" module>
.main-container {
    display: flex;
    height: 100%;
    background: #FFF;
    border-radius: 5px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    flex-direction: row;
    justify-content: flex-start;
}

.table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 10px;
}

.form-wrapper {
    display: flex;
    height: 50px;
    align-items: center;

    & [class~='el-form-item'] {
        margin-right: 10px;
        margin-bottom: 0;
    }

    & [class~='el-select'] {
        width: 200px;
    }

    & [class~='el-input'] {
        width: 200px;
    }
}

.tools-container {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    margin-bottom: 10px;
    align-items: center;

    & [class~='el-link'] {
        margin-right: 15px;
    }
}

.table-wrapper {
    flex: 1;
    width: 100%;
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 35px;
}

.tools-wrapper {
    display: flex;
    justify-content: center;
    gap: 10px;
}
</style>